<?php

namespace app\services\posts;

use app\dao\posts\PostsDao;
use app\services\BaseServices;

/**
 * 帖子
 */
class PostsServices extends BaseServices
{
    public function __construct(PostsDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 帖子列表
     * @param array $where
     * @param $uid
     * @return array
     * @throws \ReflectionException
     */
    public function pageListApp(array $where, $uid)
    {
        [ $page, $limit ] = $this->getPageValue();
        // 如果看的不是自己，只能看到审核通过的帖子
        if ($where['user_id'] != 0 && $where['user_id'] != $uid) {
            $where['status'] = 1;
        }
        $where['is_del'] = 0;
        $query = $this->dao->search($where);
        $count = $query->count();
        $dataList = $query->order('add_time desc')->with(['user'])->page($page, $limit)->select()->toArray();
        /** @var PostLikeServices $postLikeServices **/
        $postLikeServices = app()->make(PostLikeServices::class);
        foreach ($dataList as &$item) {
            $postLike = $postLikeServices->getOne(['post_id' => $item['id'], 'user_id' => $uid]);
            $item['is_like'] = isset($postLike);
        }
        return compact('dataList', 'count');
    }

    /**
     * 帖子列表
     * @param array $where
     * @return array
     * @throws \ReflectionException
     */
    public function pageListAdmin(array $where)
    {
        [$page, $limit] = $this->getPageValue();
        if ($where['status'] == -1)
            unset($where['status']);
        $where['is_del'] = 0;
        $query = $this->dao->search($where);
        $count = $query->count();
        $dataList = $query->order('add_time desc')->with(['user','postType'])->page($page, $limit)->select()->toArray();

        return compact('dataList', 'count');
    }

    public function detail($id, $uid) {
        try {
            $data = $this->dao->search(['id' => $id])->with(['user', 'postType'])->select()->toArray()[0];
            $this->update($id, ['browse' => $data['browse'] + 1]);
            /** @var PostLikeServices $postLikeServices **/
            $postLikeServices = app()->make(PostLikeServices::class);
            $postLike = $postLikeServices->getOne(['post_id' => $data['id'], 'user_id' => $uid]);
            $data['is_like'] = isset($postLike);
            return compact('data');
        }
        catch (\Exception $e) {
            return app('json')->fail("帖子不存在");
        }
    }
}